#include "addvote.h"
#include "ui_addvote.h"


AddVote::AddVote(QWidget *parent,int _userID) :
    QDialog(parent),
    ui(new Ui::AddVote),
    userID(_userID)
{
    ui->setupUi(this);
}

AddVote::~AddVote()
{
    delete ui;
}
//将用户输入的而数据保存到数据库中
int saveDataToDatabase(const QString& title,QDateTime& endTime,const QStringList& options,int CreatorID)
{
    //获取现有连接
    db.transaction();//开始事务

    try
    {
        //1,插入投票主表
        QSqlQuery query;
        query.prepare(
                    "INSERT INTO Vote (Title, CreatorID, EndTime) "
                    "OUTPUT INSERTED.VoteID "
                    "VALUES (?, ?, ?)"
                    );
        query.bindValue(0,title);
        query.bindValue(1,CreatorID);
        query.bindValue(2,endTime.toString("yyyy-MM-dd HH:mm:ss"));

        if(!query.exec()||!query.next())
        {
            throw std::runtime_error("插入投票主记录失败: " +
                            query.lastError().text().toStdString());
        }
        int voteID=query.value("VoteID").toInt();

        //2,插入投票选项
        query.prepare( "INSERT INTO VoteOption (VoteID, OptionText) "
                       "VALUES (?, ?)");
        for(const QString& option:options)
        {
            query.bindValue(0,voteID);
            query.bindValue(1,option.trimmed());//移除字符串两端的空白字符
            if (!query.exec())
            {
                            throw std::runtime_error(
                                QString("插入选项失败：%1 (选项内容：%2)")
                                    .arg(query.lastError().text())
                                    .arg(option).toStdString());
            }
        }
        db.commit();//提交事务
        return voteID;
    }
    catch (...)
        {
            db.rollback();//回滚事务
            throw;
        }
}
//点击按钮，将投票信息插入到数据库中
void AddVote::on_buttonBox_accepted()
{
    //获取输入的内容
    //投票标题
    QString voteText=ui->lineEdit->text();
    //投票持续时间单位是秒
    QString times=ui->lineEdit_2->text();
    QDateTime endTime=QDateTime::fromString(times, "yyyy-MM-dd hh:mm:ss");

    //投票的选项
    QString option=ui->lineEdit_3->text();
    //都不能为空
    if(voteText.isEmpty()||times.isEmpty()||option.isEmpty())
        return;

    //将选项进行分割
    QStringList optionlist=option.split(',');//按照逗号分割出选项
    //for test
//    qDebug()<<optionlist;

    //将这3个数据存入数据库中
    int voteID=saveDataToDatabase(voteText,endTime,optionlist,userID);
    (void)voteID;

    //给用户返回添加成功信息
    QMessageBox* message=new QMessageBox(this);
    message->setWindowTitle("新建操作");
    message->setText("新建一个投票活动成功");
    message->setIcon(QMessageBox::NoIcon);
    message->setStandardButtons(QMessageBox::Ok);
    message->exec();

    delete message;
}
